package app;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import org.w3c.dom.Element;

import android.graphics.*;
import utils.*;

public class GoogleMapDownloader implements HttpItemListener {
	private static GoogleMapDownloader GoogleMapDownloader_sharedInstance = null;
	
	private HttpQueue normalQueue = new HttpQueue();
	private HttpItem http = null;
	private Vector<String> need_to_download = new Vector<String>();
	private Dictionary<String, Bitmap> downloaded = new Hashtable<String, Bitmap>();
	
	
	public Bitmap downloadMap(String address) {
//		if (address != null) {
//			String makers = "color:red|color:red|label:C|"+address;
//			try {
//				makers = URLEncoder.encode(makers, "UTF-8");
//				String url = "http://maps.googleapis.com/maps/api/staticmap?markers="+makers+"&zoom=13&size=1000x1000&sensor=false";
//				if (downloaded.get(address) == null) {
//					if (http == null) {
//						http = normalQueue.get(url, this, address, false);
//					} else {
//						need_to_download.removeElement(address);
//						need_to_download.addElement(address);
//					}
//				} else {
//					return downloaded.get(address);
//				}
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			}
//		}
		return null;
	}

	public static GoogleMapDownloader sharedInstance() {
		if (GoogleMapDownloader_sharedInstance == null) {
			GoogleMapDownloader_sharedInstance = new GoogleMapDownloader();
		}
		return GoogleMapDownloader_sharedInstance;
	}

	public void reqeuestFinished(byte[] byteArray, Element xml,
			boolean successfull, Object param) {
		String address = (String)param;
		http = null;
		need_to_download.removeElement(address);
		Bitmap bitmap = null;
		if (successfull) {
			try {
				bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
	                    byteArray.length);
			} catch (Exception e) {
				
			}
		}
		
		if (bitmap != null) {
			downloaded.put(address, bitmap);
			AppDelegate.sharedInstance().postNotification(GoogleMapDownloaderNotificationListener.class, address, null);
		}
		
		continueQueue();
	}
	
	private void continueQueue() {
		if (need_to_download.size() > 0) {
			String address = need_to_download.elementAt(0);
			need_to_download.removeElementAt(0);
			downloadMap(address);
		}
	}
}
